/**
 * Created by charsen on 16/5/31.
 */
directives.directive('contextMenu', ["$parse", "$rootScope", "tools", "$timeout", function ($parse, $rootScope, tools, $timeout) {
    return {
        restrict: 'E',
        scope: false,
        replace: true,
        link: function (scope, element, attrs) {
            var $ele = $(element);
            scope.menus = [{
                name: ''
            }];

            // 初始化菜单,为了解决菜单在第一次被加载的时候不显示的BUG
            $ele.css({
                left: -400 + 'px',
                top: -400 + 'px'
            }).on('click', function (e) {
                $ele.find('.dropdown').dropdown('hide');
            });

            $ele.find('.dropdown').dropdown('hide');

            var processMenu = function (menus) {
                for (var i = 0; i < menus.length; i++) {
                    if (menus[i].submenusfn) {
                        menus[i].submenus = menus[i].submenusfn();
                    }
                    if (menus[i].submenus && menus[i].submenus.length) {
                        processMenu(menus[i].submenus);
                    }
                }
            }

            $rootScope.$on('CONTEXTMENU_EV', function (e, left, top, menus, ifClear) {
                if (!menus || menus.length == 0) {
                    return;
                }

                processMenu(menus);
                scope.menus = menus;

                $timeout(function () {
                    $ele.css({
                        left: left - 10 + 'px',
                        top: top - 10 + 'px',
                        zIndex: 10000
                    });
                    $ele.find('.dropdown').dropdown('show').dropdown({
                        action: 'nothing'
                    });
                }, 50);
            });

            $rootScope.$on('CONTEXTMENU_OFF_EV', function (e) {
                $ele.find('.dropdown').dropdown('hide');
                $ele.css({
                    left: -400 + 'px',
                    top: -400 + 'px'
                });
            });
        },
        templateUrl: "/trend-new-BI/app/components/common/contextMenu/contextMenuView.html"
    }
}]);